# -*- coding: utf-8 -*-
# standard
import enum
import os
import sys
from typing import List

# third
from PIL import Image
from openpyxl import Workbook
from openpyxl.drawing.image import Image as ExcelImage

# local
_P_PATH = os.path.dirname(os.path.realpath(__file__))
if _P_PATH not in sys.path:
    sys.path.append(_P_PATH)


"""
@Title:  
@File: main.py
@Author: walle 2022年10日28日 10时04分10秒
@Version: 1.0.0
@Desc: 
把图片指定位置的区域切出来粘到excel文件中.
"""


def split_image() -> List[str]:
    """
    拆分图片
    :return: _description_
    """
    img_path = os.path.join(_P_PATH, "source", "1612175613.jpg")
    img = Image.open(img_path)
    # box = (110, 778, 215, 800)
    box1 = (110, 778, 140, 800)
    box2 = (145, 778, 166, 800)
    box3 = (170, 778, 215, 800)
    target_folder = os.path.join(_P_PATH, 'target')
    if not os.path.exists(target_folder):
        os.makedirs(target_folder)
    boxes = [box1, box2, box3]
    files = []
    for i, box in enumerate(boxes):
        file = os.path.join(target_folder, f"box{i + 1}.png")
        im = img.crop(box=box)
        with open(file=file, mode='bw') as f:
            im.save(f)
        files.append(file)
    img.close()
    return files


def create_excel() -> str:
    """
    创建excel
    :return: _description_
    """
    wb = Workbook()
    first_sheet = wb.active
    first_sheet["A1"] = "幢号"
    first_sheet["A2"] = "总层数"
    first_sheet["A3"] = "所在层"
    img_paths = split_image()
    for i, img_path in enumerate(img_paths):
        img = ExcelImage(img_path)
        first_sheet.add_image(img, f"B{i + 1}")
    excel_path = os.path.join(_P_PATH, "test.xlsx")
    wb.save(filename=excel_path)
    return excel_path


if __name__ == '__main__':
    excel = create_excel()
    print(f"excel 文件保存路径: {excel}")
    pass